<?php


namespace App\Http\Controllers\android\service;


use App\Http\Controllers\admin\model\AdminModel;
use App\Http\Controllers\android\model\AdminSnModel;
use App\Http\Controllers\android\model\AppGroundModel;
use App\Http\Controllers\android\model\BindSnModel;
use App\Http\Controllers\android\model\ParentAppModel;
use App\Http\Controllers\android\model\ParentSnModel;
use App\Http\Controllers\android\model\ScreenshotModel;
use App\Http\Controllers\android\model\SettingModel;
use App\Http\Controllers\android\model\SnGradeModel;
use App\Http\Controllers\android\model\TeacherAppModel;
use App\Http\Controllers\android\model\TeacherSnModel;
use App\Http\Controllers\utils\ToolUtil;
use App\Http\Controllers\utils\UploadUtil;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\utils\LogUtil;

class SnService
{
    /**
     * 确认绑定设备
     * @param $param
     * @return false|string
     */
    public static function bindSn($param){
        try {
            $bind = BindSnModel::queryFirst(['sn_value'=>$param['sn']],['status']);
            if($bind['status']!=0){
                return ToolUtil::returnJson(301,'该设备是绑定状态');
            }
            DB::beginTransaction();
            if($param['type']==1){
                if(BindSnModel::edit(['sn_value'=>$param['sn']],['status'=>1])){
                    $admin = AdminModel::queryFirst(['id'=>$param['id']],['sn_num']);
                    AdminModel::edit(['id'=>$param['id']],['sn_num'=>$admin['sn_num']+1]);
                    SettingModel::add(['admin_id'=>$param['id'],'create_time'=>time(),'sn_value'=>$param['sn']]);
                    DB::commit();
                    return ToolUtil::returnJson(200,'绑定成功');
                }
                return ToolUtil::returnJson(300,'绑定失败');
            }else{
                $parent = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.id']);
                if($parent){
                    ParentSnModel::delete(['id'=>$parent['id']]);
                    BindSnModel::delete(['sn_value'=>$param['sn']]);
                    DB::commit();
                    return ToolUtil::returnJson(301,'用户拒绝绑定');
                }
                return ToolUtil::returnJson(300,'没有该设备');
            }
        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'网络拥堵,请稍后再试');
        }
    }

    /**
     * 获取设备信息
     * @param $param
     * @return false|string
     */
    public static function getSnInfo($param){

        $adminSn = AdminSnModel::queryFirst(['value'=>$param['sn']],['id']);
        if(!$adminSn){
            return ToolUtil::returnJson(400,'没有该设备');
        }

        $parent = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['teacher_id','sn_grade_id']);
        if(!$parent){
            return ToolUtil::returnJson(300,'该设备还没有进行绑定');
        }

        if($parent['teacher_id']){
            $field = ['t.id','a.value as sn_value','a.devices_version','a.name as sn_name','a.school','a.is_lock','a.is_reset','b.name','t.admin_id'];
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],$field);
            if($teacher){
                $snGrade = SnGradeModel::queryFirst(['id'=>$parent['sn_grade_id']],['class_name']);
                if($snGrade){
                    $teacher['grade'] = $snGrade['class_name'];
                }else{
                    $teacher['grade'] = '一年级';
                }
                return ToolUtil::returnJson(200,'成功',$teacher);
            }
        }else{
            $field = ['p.id','a.value as sn_value','a.devices_version','a.name as sn_name',
                'a.school','a.is_lock','a.is_reset','g.class_name as grade','p.admin_id'];
            $parentSn = ParentSnModel::queryLeftInfo(['a.value'=>$param['sn']],$field);
            if($parentSn){
                return ToolUtil::returnJson(200,'成功',$parentSn);
            }
        }
        return ToolUtil::returnJson(300,'该设备还没有进行绑定');
    }

    /**
     * 填写设备硬件信息
     * @param $param
     * @return false|string
     */
    public static function updateAdminSn($param){

        try {

            $address = json_decode($param['address'],true);
            $machine = json_decode($param['machine'],true);
            $hardware = json_decode($param['hardware'],true);
            $software = json_decode($param['software'],true);
            
            $data['update_time'] = time();
            if($address){
                $data['addr'] = $address['address'];
                $data['longitude'] = $address['longitude'];
                $data['latitude'] = $address['latitude'];
            }
            if($machine){
                $data['model'] = $machine['device'];
                $data['imel'] = $machine['imei'];
                $data['system'] = $machine['system_version'];
                $data['devices_version'] = $machine['firmware_version'];
                $data['orm_version'] = $machine['rom'];
                $data['screen_px'] = $machine['screen_rate'];
            }
            if($hardware){
                $data['quantity'] = $hardware['electric'];
                $data['device_memory'] = $hardware['memory'];
                $data['CPU'] = $hardware['CPU'];
                $data['is_wifi'] = $hardware['is_wifi'];
                $data['storage'] = $hardware['storage'];
                $data['use_space'] = $hardware['use_space'];
                $data['use_ram'] = $hardware['use_ram'];
                $data['wifi_ssid'] = $hardware['wifi_ssid'];
                $data['wifi_time'] = $hardware['wifi_time'];
                $data['boot_time'] = $hardware['boot_time'];
                // $data['charging'] = $hardware['charging'];//1正在充电0没有充电
            }
            if($software){
                $data['appstore_version'] = $software['appstore_version'];
                $data['updatetools_version'] = $software['updatetools_version'];
                $data['info_version'] = $software['info_version'];
                $data['jiaoguanyi_version'] = $software['jiaoguanyi_version'];
                $data['gankao_version'] = $software['gankao_version'];
                $data['learning_version'] = $software['learning_version'];
                $data['chat_version'] = $software['chat_version'];
                $data['uiuios_version'] = $software['uiuios_version'];
                $data['jpush_id'] = $software['jpush_id'];
            }

            if(AdminSnModel::edit(['value'=>$param['sn']],$data)){
                return ToolUtil::returnJson(200,'成功');
            }
            return ToolUtil::returnJson(-200,'失败');

        }catch (\Exception $exception){
            return ToolUtil::returnJson(-200,'格式错误');
        }
        
    }


    /**
     * 上传应用使用信息
     * @param $param
     * @return false|string
     */
    public static function uploadAppUseInfo($param){

        try {

            $sn = $param['sn'];
            $appInfo = json_decode($param['appInfo'],true);

            if(empty($appInfo[0]['packages'])){
                return ToolUtil::returnJson(200,'json格式错误');
            }

            $time = time();
            $date_str = date('Ymd',time());

            foreach ($appInfo as $key => $value) {
                
                if($value['packages'] != 'com.gankao.gkwxhd' && $value['packages'] != 'com.jiaoguanyi.store'){

                    $info = DB::table('t_app_use_info')->where(['date_str'=>$date_str,'sn'=>$sn,'packages'=>$value['packages']])->first(['id','use_time']);
                    if(!empty($info)){
                        $new_time = $info['use_time'] + $value['useTime'];
                        $res = DB::table('t_app_use_info')->where(['date_str'=>$date_str,'sn'=>$sn,'packages'=>$value['packages']])->update(['update_time'=>$time,'use_time'=>$new_time]);
                    }else{
                        $res = DB::table('t_app_use_info')->insert(['date_str'=>$date_str,'app_name'=>$value['app_name'],'packages'=>$value['packages'],'sn'=>$sn,'use_time'=>$value['useTime'],'add_time'=>$time]);
                    }
 
                }


            }

            if($res){
                return ToolUtil::returnJson(200,'成功');
            }else{
                return ToolUtil::returnJson(-200,'失败');
            }
            
        }catch (\Exception $exception){
            return ToolUtil::returnJson(-200,$exception->getMessage());
        }
        
    }

    /**
     * sn获取应用自启，联网，滑动，升级
     * @param $param
     * @return false|string
     */
    public static function querySnAppStart($param){
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.id','teacher_id']);
        if(!$parentSn){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }
        $field = ['t.app_package','t.is_auto','t.is_network','t.is_upgrade','t.is_lock','t.is_slide','t.visit','t.address'];
        if($parentSn['teacher_id']){
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['b.id']);
            if(!$teacher){
                return ToolUtil::returnJson(-200,'该设备没有授权老师');
            }
            $bid = $teacher['id'];
            $app = DB::table('t_teacher_app as t')
                ->whereRaw(" find_in_set({$bid},t.bind_batch_id) ")
                ->get($field);
        }else{
            $app = DB::table('t_parent_app as t')
                ->where(['sn_value'=>$param['sn']])
                ->get($field);
        }
        $data = [];
        if(count($app)){
            foreach ($app as $k=>$v){
                if(empty($v['visit'])){
                    $v['visit'] = "";
                }
                if(empty($v['address'])){
                    $v['address'] = "";
                }
                $data[$k] = $v;
            }
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * sn获取应用第三方跳转
     * @param $param
     * @return false|string
     */
    public static function querySnJump($param){
        $parentSn = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.id','teacher_id']);
        if(!$parentSn){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }
        $field = ['p.app_package','a.address'];
        if($parentSn['teacher_id']){
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['b.id']);
            if(!$teacher){
                return ToolUtil::returnJson(-200,'该设备没有授权老师');
            }
            $data = AppGroundModel::queryLikeTeacher(['a.sn_value'=>$param['sn']],['field'=>'a.batch_id','a.batch_id'=>$teacher['id']],$field);
        }else{
            $data = AppGroundModel::queryLikeParent(['a.sn_value'=>$param['sn']],$field);
        }
        if(count($data)){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 上传截屏图片
     * @param $param
     * @return false|string
     */
    public static function uploadScreenshot($param){

        $path = 'homework/Screenshot/'.$param['sn'].'-'.time().'-'.mt_rand(100,999).'.png';
        $filePath = UploadUtil::uploadAliOss($path,$param['file']);
        // $filePath = UploadUtil::uploadFile($param);

        if($filePath){
            $data = [
                // 'img'=>'http://'.$_SERVER['HTTP_HOST'].'/'.$filePath,
                'img'=>$filePath,
                'sn_value'=>$param['sn'],
                'create_time'=>time()
            ];
            if(ScreenshotModel::add($data)){
                return ToolUtil::returnJson(200,'成功');
            }
        }
        return ToolUtil::returnJson(300,'失败');
    }

    /**
     * 获取时间管控
     * @param $param
     * @return false|string
     */
    public static function getTimeControl($param){
        $parent = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.id','p.teacher_id']);
        if(empty($parent)){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }
        if($parent['teacher_id']){
            $data = [];
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['b.id']);
            if($teacher){
                $batch = $teacher['id'];
                $work = DB::table('t_time_control')->whereRaw(" find_in_set('{$batch}',batch_id) ")->where('day_type',0)->first(['start_time','end_time']);
                $rest = DB::table('t_time_control')->whereRaw(" find_in_set('{$batch}',batch_id) ")->where('day_type',1)->first(['start_time','end_time']);
            }
        }else{
            $work = DB::table('t_time_control')->where('sn_value',$param['sn'])->where('day_type',0)->first(['start_time','end_time']);
            $rest = DB::table('t_time_control')->where('sn_value',$param['sn'])->where('day_type',1)->first(['start_time','end_time']);
        }
        if($work || $rest){
            if($work){
                $data['work'] = $work;
            }else{
                $data['work']['start_time'] = '00:00';
                $data['work']['end_time'] = '00:00';
            }
            if($rest){
                $data['rest'] = $rest;
            }else{
                $data['rest']['start_time'] = '00:00';
                $data['rest']['end_time'] = '00:00';
            }
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }

    /**
     * 获取屏幕管控
     * @param $param
     * @return false|string
     */
    public static function getScreenshot($param){
        $parent = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['p.id','p.teacher_id','a.is_screen_lock']);
        if(empty($parent)){
            return ToolUtil::returnJson(-200,'该设备没有绑定');
        }
        return ToolUtil::returnJson(200,'成功',['is_screen_lock'=>$parent['is_screen_lock']]);
    }

    /**
     * 获取首页banner图
     * @return false|string
     */
    public static function getBanner(){
        $data = DB::table('t_banner')->first(['banner_name','banner_img','vertical_img']);
        if($data){
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }


    /**
     * sn获取用户设备头像信息
     * @return false|string
     */
    public static function getUserAvatarInfo($param){

        $adminSn = AdminSnModel::queryFirst(['value'=>$param['sn']],['id']);
        if(!$adminSn){
            return ToolUtil::returnJson(400,'没有该设备');
        }

        $parent = ParentSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],['admin_id','teacher_id','sn_grade_id']);
        if(!$parent){
            return ToolUtil::returnJson(300,'该设备还没有进行绑定');
        }

        $username = DB::table('t_admin')->where('id',$parent['admin_id'])->first(['username']);

        if($username){
            $name = $username['username'];
        }else{
            $name = '';
        }

        if($parent['teacher_id']){
            $field = ['a.id','a.avatar'];
            $teacher = TeacherSnModel::queryLeftAdminSn(['a.value'=>$param['sn']],$field);
            if($teacher){
                $snGrade = SnGradeModel::queryFirst(['id'=>$parent['sn_grade_id']],['class_name']);
                if($snGrade){
                    $teacher['grade'] = $snGrade['class_name'];
                }else{
                    $teacher['grade'] = '未设置';
                }
                $teacher['username'] = $name;
                return ToolUtil::returnJson(200,'成功',$teacher);
            }
        }else{
            $field = ['a.id','a.avatar','g.class_name as grade'];
            $parentSn = ParentSnModel::queryLeftInfo(['a.value'=>$param['sn']],$field);
            if($parentSn){
                $parentSn['username'] = $name;
                return ToolUtil::returnJson(200,'成功',$parentSn);
            }
        }
        return ToolUtil::returnJson(300,'该设备还没有进行绑定');

    }


    /**
     * 保存sn和uid
     * @return false|string
     */
    public static function saveSnUid($param){

        $sn = ToolUtil::filterStr($param['sn']);
        $uid = ToolUtil::filterStr($param['uid']);
        $grade = ToolUtil::filterStr($param['grade']);
        $json = json_decode($param['card_info'],true);
        if(empty($json[0]['specification_id'])){
            return ToolUtil::returnJson(300,'card_info信息json格式错误');
        }

        $data = ['uid'=>$uid,'card_info'=>$param['card_info']];
        $sn_uid_data = DB::table('t_sn_uid')->where('sn',$sn)->first(['id']);

        if($sn_uid_data){
            $data['update_time'] = time();
            $res = DB::table('t_sn_uid')->where('sn',$sn)->update($data);
        }else{
            $data['sn'] = $sn;
            $data['add_time'] = time();
            $res = DB::table('t_sn_uid')->insert($data);
        }

        if($res){
            return ToolUtil::returnJson(200,'成功');
        }else{
            return ToolUtil::returnJson(300,'失败');
        }
        
    }

    /**
     * 取消所有套餐
     * @return false|string
     */
    public static function deleteSnUid($param){

        $sn = ToolUtil::filterStr($param['sn']);
        $sn_data = DB::table('t_admin_sn')->where('value',$sn)->first(['uid','card_info','grade']);
        $res = DB::table('t_sn_uid')->where('sn',$sn)->delete();
        if($res){

            $param['userId'] = 0;
            $param['remark'] = '取消所有套餐成功';
            $param['details'] = ToolUtil::handleSuccessOrError(['sn'=>$param['sn']]);
            LogUtil::addAdminLog($param);

            return ToolUtil::returnJson(200,'成功');
        }else{
            return ToolUtil::returnJson(300,'失败');
        }
        
    }


    /**
     * 获取sn和uid信息
     * @return false|string
     */
    public static function getSnUid($param){

        $sn = ToolUtil::filterStr($param['sn']);
        $res = DB::table('t_sn_uid')->where('sn',$sn)->first(['uid','card_info','grade']);
        if($res){
            $res['card_info'] = json_decode($res['card_info'],true);
            return ToolUtil::returnJson(200,'成功',$res);
        }else{
            return ToolUtil::returnJson(300,'没有数据');
        }
        
    }


    /**
     * 获取batch
     * @return false|string
     */
    public static function getBatch($param){

        $sn = ToolUtil::filterStr($param['sn']);

        $sn_data = DB::table('t_teacher_sn as t')
            ->leftJoin('t_admin_sn as a', 'a.id', '=', 't.admin_sn_id')
            ->where(['a.value' => $sn])
            ->first(['t.batch_id']);

        if($sn_data){
            return ToolUtil::returnJson(200,'成功',$sn_data);
        }

        return ToolUtil::returnJson(300,'没有数据');

    }




}